extends CharacterBody2D
# -----------------------变量声明------------------------- # 
@export var speed=20
@export var limit=0.5
@export var health=5
@export var knockbackPower:int=500
@onready var endPoint:Marker2D=$Marker2D
@onready var animation=$AnimationPlayer


var startPosition
var endPosition
var isDeath:=false
var isHurt:=false
# -----------------------生命周期------------------------- # 
func _ready() -> void:
  startPosition=position
  endPosition=endPoint.global_position

func _physics_process(_delta: float) -> void:
  if isDeath:return
  move()
  move_and_slide()
  updateAnimation()
# -----------------------响应函数------------------------- # 
func move():
  var dir=(endPosition-position)
  if dir.length()<limit:turnBack()
  velocity=dir.normalized()*speed

func turnBack():
  var temp=endPosition
  endPosition=startPosition
  startPosition=temp

func updateAnimation():
  var dir='向下'
  if velocity.y<0:dir='向上'
  if velocity.x<0:dir='向左'
  elif velocity.x>0:dir='向右'
  animation.play(dir+'走')

func hurt(area):
  print('hurt')
  isHurt=true
  health-=1
  if health<=0:death()
  knockback(area.get_parent().get_parent().position)
  await get_tree().create_timer(0.2).timeout
  isHurt=false
  
# 击退
func knockback(playerPos:Vector2):
  var direc=(position-playerPos).normalized()*knockbackPower
  velocity=direc
  move_and_slide()

func death():
  $HitBox.set_deferred("monitorable",false)
  isDeath=true
  animation.play('死亡')
  await animation.animation_finished
  queue_free()

func _on_hurt_box_area_entered(area: Area2D) -> void:
  if area==$HitBox or isDeath :return
  if !isHurt:hurt(area)
